package com.yystar.support.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	public static Cookie getCookie(HttpServletRequest request, String name) {
		Cookie cookies[] = request.getCookies();
		if (cookies == null || name == null || name.length() == 0) {
			return null;
		}
		for (int i = 0; i < cookies.length; i++) {
			if (name.equals(cookies[i].getName())) {
				return cookies[i];
			}
		}
		return null;
	}

	public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, Cookie cookie) {
		if (cookie != null) {
			cookie.setPath(getPath(request));
			cookie.setValue("");
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
	}

	public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) {
		setCookie(request, response, name, value, 15778463);
	}

	public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, int maxAge) {
		/* replace Cookie with response.setHeader to fix IE bug */
		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		calendar.add(Calendar.SECOND, maxAge);
		DateFormat format = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US);
		format.setTimeZone(TimeZone.getTimeZone("GMT"));
		String expires = format.format(calendar.getTime());
		String path = getPath(request);
		String cookie = name + "=\"" + value + "\"; path=" + path + "; expires=" + expires + "; max-age=" + maxAge;
		response.setHeader("Set-Cookie", cookie);
	}

	private static String getPath(HttpServletRequest request) {
		/*
		 * String path = request.getContextPath(); return (path == null ||
		 * path.length() == 0) ? "/" : path;
		 */
		return "/";
	}

}
